package com.joker.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.joker.pojo.Message;
import com.joker.pojo.Messages.*;
import com.joker.pojo.User;
import com.joker.pojo.UserFried;
import com.joker.service.UserFriendService;
import com.joker.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userservice;

    @Autowired
    @Qualifier("UserFriendServiceImpl")
    private UserFriendService userFriendService;
    //账号注册

    @RequestMapping("/selectme")
    @ResponseBody
    public String selectme(@RequestParam("userid") String userid){
        User me=new User();

        me=userservice.selectme(Integer.parseInt(userid));
        JSONObject jsonObject=(JSONObject) JSONObject.toJSON(me);
        return jsonObject.toString();
    }
    @RequestMapping(value = "/adduser",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String adduser(@RequestParam("userid") Integer userid,@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("email") String email){
        User user=new User();
        user.setUserid(userid);
        user.setUsername(username);
        user.setPassword(password);
//        给个默认头像
        user.setHeadimg("access/20211020222952.jpg");
        user.setEmail(email);
        if(userservice.CheckIfregister(user)){
            userservice.adduser(user);
            AddUser successadduser=new AddUser();
            successadduser.setCode("200");
            successadduser.setMessage("成功注册");
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(successadduser);
            return jsonObject.toJSONString();
        }
        else {
            //该账号已存在，无需注册，
            System.out.println("账号已存在");
            AddUser erroradduser=new AddUser();
            erroradduser.setCode("200");
            erroradduser.setMessage("账号已存在");
            JSONObject jsonObject= (JSONObject) JSONObject.toJSON(erroradduser);
            return jsonObject.toJSONString();
        }

    }

    //账号登陆
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestParam("userid") Integer userid,@RequestParam("password") String password){
        User user= new User();
        user.setUserid(userid);
        user.setPassword(password);
        if(userservice.login(user)){
            Login successlogin=new Login();
            successlogin.setMessage("success");
            successlogin.setCode("200");
            successlogin.setToken("");
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(successlogin);
            System.out.println(jsonObject);
           return jsonObject.toJSONString();

        }
        else {
            Login errorlogin=new Login();
            errorlogin.setMessage("error");
            errorlogin.setCode("200");
            errorlogin.setToken("");
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(errorlogin);
            System.out.println(jsonObject);
            //
            return jsonObject.toJSONString();
        }
    }

    //查询存不存在这个
    @RequestMapping(value="/selectmyfriendid",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String selectmyfriendid(@RequestParam("userid") Integer userid) {
        UserFriendMessage userFriendMessage = new UserFriendMessage();
        UserFried userFried = new UserFried();
        userFried.setUserid(userid);
        userFried.setIffriend(1);
        ArrayList<UserFried> list = this.userFriendService.selectmyfriendid(userFried);
        JSONObject jsonObject;
        if (list.size() <= 0) {
            System.out.println("没有找到好友");
            userFriendMessage.setCode("200");
            userFriendMessage.setMessage(new ArrayList());
            jsonObject = (JSONObject)JSONObject.toJSON(userFriendMessage);
            return jsonObject.toJSONString();
        } else {
            System.out.println("输出该用户的frienduser");
            Iterator var5 = list.iterator();

            while(var5.hasNext()) {
                UserFried value = (UserFried)var5.next();
                System.out.println("用户");
            }

            userFriendMessage.setMessage(list);
            System.out.println(list);
            userFriendMessage.setCode("200");
            String uulist = (String) JSON.toJSON(userFriendMessage);
            return uulist;
        }
    }

    @RequestMapping(value = "/selectnewmessage",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String selectnewmessage(@RequestParam("userid") String userid){
        UserFried temp=new UserFried();
        //把自己的id当friendid来传反查谁申请添加自己为好友
        System.out.println("userid是"+userid);

        temp.setFriendid(Integer.parseInt(userid));
        temp.setIffriend(0);

        ArrayList<UserFried> friendlist=userFriendService.selectyanzhen(temp);
        for (UserFried tt:friendlist) {
            System.out.println(tt);
        }
        String rest=JSON.toJSONString(friendlist);
        return rest;
    }
    @RequestMapping(value="/addfriend",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String adduserfriend(@RequestParam("userid") Integer userid, @RequestParam("friendid") Integer friendid) {
        AddUserFriend addUserFriend = new AddUserFriend();
        UserFried userFried = new UserFried();
        userFried.setUserid(userid);
        userFried.setFriendid(friendid);
        userFried.setIffriend(1);
        ArrayList<UserFried> list = this.userFriendService.selectmyfriendid(userFried);
        userFried.setIffriend(0);
        ArrayList<UserFried> list1 = this.userFriendService.selectmyfriendid(userFried);
        Iterator var7 = list.iterator();

        while(var7.hasNext()) {
            UserFried value = (UserFried)var7.next();
            System.out.println(value);
        }

        JSONObject jsonObject;
        if (list.size() > 0) {
            System.out.println("list的size" + list.size());
            addUserFriend.setCode("200");
            addUserFriend.setMessage("该好友已存在");
            System.out.println("该好友已存在");
            jsonObject = (JSONObject)JSONObject.toJSON(addUserFriend);
            return jsonObject.toJSONString();
        } else if (list1.size() > 0) {
            addUserFriend.setCode("200");
            addUserFriend.setMessage("该好友申请已发出");
            System.out.println("该好友申请已发出");
            jsonObject = (JSONObject)JSONObject.toJSON(addUserFriend);
            return jsonObject.toJSONString();
        } else {
            //自己好友关系添加一台记录
            this.userFriendService.adduserfriend(userFried);
            //对方的好友关系添加一条记录
            userFried.setFriendid(userid);
            userFried.setUserid(friendid);
            this.userFriendService.adduserfriend(userFried);
            System.out.println("好友申请已发出");
            addUserFriend.setMessage("好友申请以发出");
            addUserFriend.setCode("200");
            jsonObject = (JSONObject)JSONObject.toJSON(addUserFriend);
            return jsonObject.toJSONString();
        }
    }
    //修改个人信息
    @RequestMapping(value = "/updatemyxinxi",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String updatemyxinxi(@RequestParam("userid") String userid,@RequestParam("username") String username,@RequestParam("email") String email,@RequestParam("password") String password)
    {
        User me=new User();
        me.setUserid(Integer.parseInt(userid));
        me.setUsername(username);
        me.setPassword(password);
        me.setEmail(email);
        //修改自己的个人信息
       int rest= userservice.updatemyxinxi(me);
       PublicMessage message=new PublicMessage();
       message.setCode("200");
       if(rest>0){
           message.setMessage("修改成功");
       }else {
           message.setMessage("修改失败");
       }
       String mess=JSON.toJSONString(message);
        return mess;
    }
    //上传替换图片
    //修该个人头像
    @RequestMapping(value = "/updateheadimg",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String updateheadimg(@RequestParam("userid") String userid,@RequestParam("headimg") MultipartFile headfile,HttpServletRequest request){
        //生成时间戳

        System.out.println("userid是"+userid);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        System.out.println(date);

        String filename = headfile.getOriginalFilename();//得到文件名
       String lastfilename= filename.substring(filename.lastIndexOf("."));
        System.out.println("输出文件后缀名"+lastfilename);
        System.out.println("文件名"+filename);
        User tempuser=new User();

        // 判断文件是否为空
        if (!headfile.isEmpty()) {
            try {
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/access/")+date+lastfilename;
                System.out.println("输出地址"+filePath);
                tempuser.setUserid(Integer.parseInt(userid));
                tempuser.setHeadimg("access/"+date+lastfilename);
                userservice.updateheadimg(tempuser);
                // 转存文件
                headfile.transferTo(new File(filePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        PublicMessage message=new PublicMessage();
        message.setCode("200");
        message.setMessage("ok");
        JSONObject jsonObject=new JSONObject();
        jsonObject.toJSONString(message);
        return jsonObject.toString();
    }


}
